package com.song.book.utils;


import cn.hutool.core.lang.UUID;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Objects;

/**
 * @Author 宋伟宁
 * @Date 2023/10/23
 * @Version 1.0
 **/
public class JwtUtils {

    private static final long time = 1000 * 60 * 1L;
    private static final String sign = "tony";

    /**
     * 生成token
     * @return
     */
    public  static String createToken(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String token =
                jwtBuilder
                        //设置头信息： typ：类型为jwt alg：加密的算法：HS256
                        .setHeaderParam("typ","jwt")
                        .setHeaderParam("alg","HS256")
                        //设置主体
                        .setSubject("admin-test")
                        //设置内容
                        .claim("username","tom")
                        .claim("role","user")
                        //设置有效期
                        .setExpiration(new Date(System.currentTimeMillis() + time))
                        //设置id
                        .setId(UUID.fastUUID().toString())
                        //设置加密的算法
                        .signWith(SignatureAlgorithm.HS256,sign)
                        //进行拼接和加密
                        .compact();
           return token;
    }

    /**
     * 验证token是否失效
     * @param token
     * @return
     */
    public static boolean checkToken(String token){
        if(Objects.isNull(token)) return false;
        JwtParser parser = Jwts.parser();
            Jws<Claims> claimsJws = parser.setSigningKey(sign).parseClaimsJws(token);
        return true;
    }
}